package com.example.demo.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.example.demo.entity.response.Result;
import com.example.demo.entity.response.ResultCodeEnum;
import com.example.demo.unique.exception.UniqueFileException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @Author: LJP
 * @Description:        全局异常处理类
 * @Date: Created in 20:50 2021/11/30
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 字段必传校验异常统一处理
     * @param e 异常
     * @return  返回结果
     */
    @ExceptionHandler(RequiredFieldIsNullException.class)
    public Result<Object> RequiredFieldIsNullException(RequiredFieldIsNullException e){
        return Result.failure(ResultCodeEnum.FAIL).data(e.getMessage());
    }

    /**
     * 字段唯一校验异常处理
     * @param e 异常
     * @return  返回结果
     */
    @ExceptionHandler(UniqueFileException.class)
    public Result<Object>UniqueFileException(UniqueFileException e){
        return Result.failure(ResultCodeEnum.FAIL).data(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public Result<Object> handlerNotLoginException(NotLoginException e, HttpServletRequest request, HttpServletResponse response){

        //打印堆栈，以供调试
        e.printStackTrace();

        //定义错误信息
        String message;

        switch (e.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = "未提供token";
                break;
            case NotLoginException.INVALID_TOKEN:
                message = "token无效";
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = "token已过期";
                break;
            case NotLoginException.BE_REPLACED:
                message = "token已被顶下线";
                break;
            case NotLoginException.KICK_OUT:
                message = "token已被踢下线";
                break;
            default:
                message = "当前会话未登录";
                break;
        }

        return Result.failure(ResultCodeEnum.FAIL).data(message);
    }

    /**
     * Service exception result.
     * 接口限流异常
     *
     * @param e the e
     * @return the result
     */
    @ExceptionHandler(ServiceException.class)
    public Result<Object> serviceException(ServiceException e) {
        return Result.failure(e.getMessage());
    }

}
